<?php
//
// +---------------------------------------------------------+
// | 开发组
// +---------------------------------------------------------+
// | Copyrigh  (c)  2020 The PHP Group
// +---------------------------------------------------------+
// | 后台菜单
// +---------------------------------------------------------+
// | zxc
// | php后端开发
// |
// +———————————————————+
//

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;

class AdminRole extends Model
{

    protected $table = 'admin_role';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    // 获取列表-分页
    public static function getList($where = [], $limit = 20)
    {
        $start = $where['end'] ? strtotime($where['start']) : 0;
        $end = $where['end'] ? strtotime($where['end']) : time();
        $db = self::whereBetween('created_at', [$start, $end]);

        if (isset($where['name']) && !empty($where['name'])) {
            $db->where('name', trim($where['name']));
        }
        $list = $db->orderBy('sort', 'asc')->paginate($limit);
        return $list;
    }

    // 获取列表
    public static function getAll($where = [])
    {
        $list = self::where($where)->orderBy('sort', 'asc')->get();
        return $list;
    }

    // 获取单条信息
    public static function getInfoById($id)
    {
        $info = self::where(['id' => $id])->first();
        if ($info) {
            $info['auth'] = json_decode($info['auth'], true);
            return $info;
        }
        return [];
    }

    // 获取单条信息
    public static function getInfoByKey($key, $value)
    {
        return self::where([$key => $value])->first();
    }

    // 添加
    public static function addInfo($dataArr)
    {
        $result = self::create($dataArr);
        return $result;
    }

    // 更新
    public static function updateById($id, $dataArr)
    {
        $info['name'] = $dataArr['name'];
        $info['auth'] = $dataArr['role'] ? json_encode(array_values($dataArr['role'])) : '[]';
        $info['note'] = $dataArr['note'];
        $info['sort'] = $dataArr['sort'];
        $result = self::where(['id' => $id])->update(array_filter($info));
        return $result;
    }

    public static function upInfo($dataArr)
    {
        $info['name'] = $dataArr['name'];
        $info['auth'] = $dataArr['auth'] ? json_encode(array_values($dataArr['auth'])) : '[]';
        $info['note'] = $dataArr['note'];
        $info['sort'] = $dataArr['sort'];
        if ($dataArr['id']) {
            return self::where(['id' => $dataArr['id']])->update(array_filter($info));
        } else {
            $info['created_at'] = time();
            return self::insert(array_filter($info));
        }
    }

    // 删除
    public static function deleteById($id)
    {
        $result = self::where('id', $id)->delete();
        return $result;
    }
}